package com.example.himalaya.view.fragments;

import android.content.Intent;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.himalaya.R;
import com.example.himalaya.view.activity.PlayerViewActivity;
import com.example.himalaya.view.adapters.TrackListAdapter;
import com.example.himalaya.base.BaseApplication;
import com.example.himalaya.base.BaseFragment;
import com.example.himalaya.view.callback.ISearchViewCallBack;
import com.example.himalaya.presenters.PlayerPresenter;
import com.example.himalaya.presenters.SearchPresenter;
import com.example.himalaya.view_component.UILoader;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.ximalaya.ting.android.opensdk.model.album.Album;
import com.ximalaya.ting.android.opensdk.model.album.Announcer;
import com.ximalaya.ting.android.opensdk.model.track.Track;
import com.ximalaya.ting.android.opensdk.model.word.HotWord;
import com.ximalaya.ting.android.opensdk.model.word.QueryResult;

import net.lucode.hackware.magicindicator.buildins.UIUtil;

import java.util.List;
import java.util.Objects;

public class SearchViewResultTrackFragment extends BaseFragment implements ISearchViewCallBack {

    private UILoader mUiLoader = null;
    private RecyclerView mAlbumListRv;
    private TrackListAdapter mTrackListAdapter;
    private SearchPresenter mSearchPresenter;
    private TwinklingRefreshLayout mRefreshLayout;

    @Override
    protected View onSubViewLoaded(LayoutInflater inflater, ViewGroup container) {

        mUiLoader = initUILoader(inflater);

        initData();

        return mUiLoader;
    }

    private void initData() {
        if (mSearchPresenter != null) {
            mSearchPresenter.doSearchTrack();

            mUiLoader.updateStatus(UILoader.UIStatus.LOADING);
        }
    }

    private UILoader initUILoader(final LayoutInflater inflater) {
        if (mUiLoader == null) {
            mUiLoader = new UILoader(BaseApplication.getAppContext()) {
                @Override
                protected View getSuccessView(ViewGroup container) {
                    return createSuccessView(inflater, container);
                }
            };
        }

        return mUiLoader;
    }

    private View createSuccessView(LayoutInflater inflater, ViewGroup container) {

        View mSuccessView = inflater.inflate(R.layout.search_reasult_album_container, container, false);

        initSuccessVariable(mSuccessView);

        initSuccessAdapter();

        initSuccessPresenter();

        initSuccessListener();


        initSuccessView();

        return mSuccessView;
    }

    private void initSuccessPresenter() {
        mSearchPresenter = SearchPresenter.getSearchPresenter();
        mSearchPresenter.registerViewCallback(this);
    }


    private void initSuccessView() {
        // 不能下拉刷新
        mRefreshLayout.setEnableRefresh(false);

//        BezierLayout bezierLayout = new BezierLayout(this);
//        mRefreshLayout.setHeaderView(bezierLayout);
        mRefreshLayout.setMinimumHeight(140);
        mRefreshLayout.setOverScrollBottomShow(false);

        // 设置布局管理器
        // 1.设置布局管理
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(BaseApplication.getAppContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mAlbumListRv.setLayoutManager(linearLayoutManager);

        // 给每个item设置外边距
        mAlbumListRv.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.top = UIUtil.dip2px(view.getContext(), 5);
                outRect.bottom = UIUtil.dip2px(view.getContext(), 5);
                outRect.left = UIUtil.dip2px(view.getContext(), 5);
                outRect.right = UIUtil.dip2px(view.getContext(), 5);
            }
        });
    }

    private void initSuccessListener() {
        mTrackListAdapter.setItemClickListener(new TrackListAdapter.ItemClickListener() {
            @Override
            public void onItemClick(List<Track> detailData, int position) {
                // 设置播放器的数据
                PlayerPresenter playerPresenter = PlayerPresenter.getPlayerPresenter();

                playerPresenter.setPlayList(detailData, position);

                // 跳转到播放器界面
                Intent intent = new Intent(Objects.requireNonNull(getActivity()), PlayerViewActivity.class);

                startActivity(intent);
            }
        });

        // 上拉加载更多的事件
        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);

//                LogUtil.d(TAG, "Load more...");

                if (mSearchPresenter != null) {
                    mSearchPresenter.loadMoreTrack();
                }

            }
        });
    }

    private void initSuccessAdapter() {
        mTrackListAdapter = new TrackListAdapter();

        mAlbumListRv.setAdapter(mTrackListAdapter);
    }

    private void initSuccessVariable(View mSuccessView) {
        mAlbumListRv = mSuccessView.findViewById(R.id.search_result_album_rv);
        mRefreshLayout = mSuccessView.findViewById(R.id.search_result_album_refresh_layout);
    }

    @Override
    public void onSearchAlbumLoaded(List<Album> result) {

    }

    @Override
    public void onSearchTrackLoaded(List<Track> result) {
        handleSearchResult(result);
    }

    @Override
    public void onSearchAnnouncerLoaded(List<Announcer> result) {

    }

    private void handleSearchResult(List<Track> result) {
        if (result != null) {
            if (result.size() == 0) {
                // 数据为空
                if (mUiLoader != null) {
                    mUiLoader.updateStatus(UILoader.UIStatus.EMPTY);
                }
            } else {
                // 如果数据不为空就设置数据
                mTrackListAdapter.setData(result);
                mUiLoader.updateStatus(UILoader.UIStatus.SUCCESS);
            }
        } else {
            mUiLoader.updateStatus(UILoader.UIStatus.ERROR);
        }
    }


    @Override
    public void onHotWorldLoaded(List<HotWord> hotWordList) {

    }

    @Override
    public void onLoadMoreAlbumResult(List<Album> result, boolean isOkay) {

    }

    @Override
    public void onLoadMoreAnnouncerResult(List<Announcer> result, boolean isOkay) {

    }

    @Override
    public void onLoadMoreTrackResult(List<Track> result, boolean isOkay) {
        // 处理加载跟多的结果
        if (mRefreshLayout != null) {
            mRefreshLayout.finishLoadmore();
        }
        if (isOkay) {
            handleSearchResult(result);
        } else {
            Toast.makeText(BaseApplication.getAppContext(), "没有更多内容", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void onRecommendWorldLoaded(List<QueryResult> keyWordList) {

    }

    @Override
    public void onError(int errorCode, String errorMsg) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mSearchPresenter != null) {
            mSearchPresenter.unRegisterViewCallback(this);
        }

        if (mTrackListAdapter != null) {
            mTrackListAdapter.setItemClickListener(null);
        }
    }
}
